/*
 * @Description: 光盘管理弹窗
 * @Author: Rfan
 * @Date: 2022-06-25 15:02:05
 * @LastEditTime: 2022-06-27 17:09:46
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Col, message, Modal, Row, Space, Table } from 'antd';
import classNames from 'classnames/bind';
import type { FC } from 'react';
import type { ColumnsType } from 'antd/lib/table';
import { useFormatMessage } from '@/utils/intlHelpers';
import { deleteDiskType, fetchDiskTypeList } from '@/api/archives/export';
import { delItemByIdArray, editItemById, getListItemValue, insertItem } from '@/utils/list';
import AddCDDialog from './components/AddCD';
import EditCDDialog from './components/EditCD';
import type { ICommonDialog } from '@/interfaces/global';

import styles from './styles/main.module.scss';

const cx = classNames.bind(styles);

export const unitList = [
  { name: 'GB', value: 0 },
  { name: 'MB', value: 1 }
];

interface CDTypeMgtDialogProps extends ICommonDialog {}

const CDTypeMgtDialog: FC<CDTypeMgtDialogProps> = (props) => {
  const { visible, onClose } = props;
  const formatMessage = useFormatMessage();

  const columns: ColumnsType = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      align: 'center'
    },
    {
      title: '光盘名称',
      dataIndex: 'diskName',
      key: 'diskName',
      align: 'center'
    },
    {
      title: '光盘容量',
      dataIndex: 'diskVolume',
      key: 'diskVolume',
      align: 'center',
      render: (val, record: any) => (record.volumeType === 1 ? '-' : val)
    },
    {
      title: '单位',
      dataIndex: 'volumeUnit',
      key: 'volumeUnit',
      align: 'center',
      render: (val, record: any) =>
        record.volumeType === 1 ? '' : getListItemValue(val, unitList, 'name', 'value')
    },
    {
      title: '创建人',
      dataIndex: 'operatorName',
      key: 'operatorName',
      align: 'center'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center'
    },
    {
      title: formatMessage('tableAction'),
      key: 'action',
      align: 'center',
      render: (_text, record: any) => {
        return (
          <Space>
            <Button
              type="link"
              onClick={() => {
                showEditDialog(record);
              }}
            >
              编辑
            </Button>
            <Button
              type="text"
              danger
              onClick={() => {
                delDisk(record.id);
              }}
            >
              删除
            </Button>
          </Space>
        );
      }
    }
  ];

  // 表格数据
  const [dataSource, setDataSource] = useState([]);
  // 添加光盘弹窗
  const [addCDTypeVisible, setAddCDTypeVisible] = useState(false);
  // 编辑光盘弹窗
  const [editCDTypeVisible, setEditCDTypeVisible] = useState(false);
  // 编辑的数据
  const [editData, setEditData] = useState({});

  useEffect(() => {
    if (visible) {
      fetchDiskTypeList({}).then((res) => {
        setDataSource(res.data);
      });
    }
  }, [visible]);

  /**
   * @description: 关闭弹窗
   */
  const onCancel = () => {
    onClose();
  };

  /**
   * @description: 展示模板弹窗方法
   */
  const showAddCDDialog = () => {
    setAddCDTypeVisible(true);
  };

  /**
   * @description: 关闭模板弹窗方法
   */
  const closeAddCDDialog = (data: any) => {
    if (data) {
      setDataSource((state) => insertItem(data, state));
    }
    setAddCDTypeVisible(false);
  };

  const showEditDialog = (data: any) => {
    setEditData(data);
    setEditCDTypeVisible(true);
  };
  const closeEditDialog = (data: any) => {
    if (data) {
      setDataSource((state) => editItemById(data.id, data, state));
    }
    setEditCDTypeVisible(false);
  };

  const delDisk = (id: number) => {
    deleteDiskType(id).then((res) => {
      message.success('删除成功');
      const ids = res.data.map((item: string) => parseInt(item, 10));
      setDataSource((state) => delItemByIdArray(ids, state));
    });
  };

  return (
    <Modal title="光盘参数" visible={visible} width={700} onCancel={onCancel}>
      <Row className={cx('title')} justify="space-between" align="middle">
        <Col>已有光盘参数列表</Col>
        <Col>
          <Button
            type="primary"
            onClick={() => {
              showAddCDDialog();
            }}
          >
            添加
          </Button>
        </Col>
      </Row>
      <Table dataSource={dataSource} columns={columns} rowKey="id" pagination={false} bordered />
      {useMemo(
        () => (
          <AddCDDialog
            visible={addCDTypeVisible}
            onClose={(data) => {
              closeAddCDDialog(data);
            }}
          />
        ),
        [addCDTypeVisible]
      )}
      {useMemo(
        () => (
          <EditCDDialog
            visible={editCDTypeVisible}
            data={editData}
            onClose={(data) => {
              closeEditDialog(data);
            }}
          />
        ),
        [editCDTypeVisible]
      )}
    </Modal>
  );
};

export default CDTypeMgtDialog;
